<script lang="ts" setup>
import type { FormInstance } from 'element-plus';

import { onMounted, reactive, ref, watch } from 'vue';

import { Page } from '@vben/common-ui';

import { ElMessage } from 'element-plus';

import {
  reqAccountList,
  reqGroupList,
  reqPlatformList,
} from '#/api/exchange-center';
import { reqCancelOrder } from '#/api/order-collection';
import { reqSupportedSymbolByName } from '#/api/system';

interface IPlatform {
  id: number;
  name: string;
}
const exchangeList = ref<IPlatform[]>([]);
const getPlatformList = async () => {
  const platformList = await reqPlatformList();
  exchangeList.value = platformList.list;
};

const loading = ref(false);

const formRef = ref<FormInstance>();
interface IFrom {
  exchange?: IPlatform | null;
  platform_id?: number;
  symbol: string;
  groups: string[];
  accounts: string[];
}
const form = reactive<IFrom>({
  exchange: null,
  symbol: '',
  groups: [],
  accounts: [],
});

const rules = reactive({
  exchange: [{ required: true, message: '请选择平台', trigger: 'blur' }],
  symbol: [{ required: true, message: '请选择下单品种', trigger: 'blur' }],
  groups: [{ required: true, message: '请选择组', trigger: 'change' }],
  accounts: [{ required: true, message: '请选择户', trigger: 'change' }],
});
interface ISymbol {
  id: number;
  symbol: string;
}
interface IAccountAndGroup {
  id: string;
  name: string;
  account?: string[];
}
interface IAccount {
  id: number;
  account: string;
}
const currentSymbols = ref<ISymbol[]>([]);
const currentGroups = ref<IAccountAndGroup[]>([]);
const currentAccounts = ref<IAccount[]>([]);

watch(
  () => exchangeList.value,
  () => {
    // getPlatformList();
  },
);

const getGroups = async () => {
  // 获取组
  const curGroups = await reqGroupList();
  currentGroups.value = curGroups.list;
};
getGroups();
// 获取品种、用户、组
const getAccountAndGroup = async () => {
  // 获取当前平台品种
  const curSupportSymbol = await reqSupportedSymbolByName(form.exchange!.name);
  currentSymbols.value = curSupportSymbol;
  // // 获取组
  // const curGroups = await reqGroupList();
  // currentGroups.value = curGroups.list;
  // 获取户
  const curPlatformAccount = await reqAccountList({
    platform_id: form.exchange!.id,
  });
  currentAccounts.value = curPlatformAccount.list;
};

// const currentGroups = computed(() => {
//   return currentAccountAndGroups.value.map((item) => item.group);
// });

// const currentAccounts = computed(() => {
//   return currentAccountAndGroups.value.flatMap((item) => item.user);
// });

onMounted(() => {
  // getAccountAndGroup();
  getPlatformList();
});

watch([() => form.groups, () => form.accounts], (val) => {
  if (val[0].length > 0 || val[1].length > 0) {
    formRef.value!.clearValidate('accounts');
    formRef.value!.clearValidate('groups');
  }
});

watch(
  () => form.exchange,
  () => {
    form.groups = [];
    form.accounts = [];
  },
);
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  await formEl.validate((valid) => {
    if (valid) {
      const params = {
        platform_id: form.exchange!.id,
        symbol: form.symbol,
        groups: form.groups,
        accounts: form.accounts,
      };
      withdrawAnOrder(params);
    } else {
      // console.log('error submit!', fields);
    }
  });
};

// const resetForm = (formEl: FormInstance | undefined) => {
//   if (!formEl) return;
//   formEl.resetFields();
// };

// 撤销订单
const withdrawAnOrder = async (data: IFrom) => {
  loading.value = true;

  reqCancelOrder(data)
    .then(() => {
      ElMessage({
        message: '操作成功',
        type: 'success',
      });
      // resetForm(formRef.value);
    })
    .finally(() => {
      loading.value = false;
    });
};
</script>

<template>
  <Page class="">
    <el-card>
      <div style="width: 400px" class="flex justify-center">
        <el-form
          :model="form"
          class="revoke-form"
          label-width="auto"
          label-position="right"
          :rules="rules"
          ref="formRef"
        >
          <el-form-item label="平台" prop="exchange">
            <el-select
              v-model="form.exchange"
              placeholder="请选择操作平台"
              value-key="id"
              @change="getAccountAndGroup()"
            >
              <el-option
                v-for="item in exchangeList"
                :key="item.id"
                :label="item.name"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="下单品种" prop="symbol">
            <el-select v-model="form.symbol" placeholder="请选择下单品种">
              <el-option
                v-for="item in currentSymbols"
                :key="item.id"
                :label="item.symbol"
                :value="item.symbol"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="组"
            :prop="form.accounts.length > 0 ? '' : 'group'"
          >
            <el-select
              v-model="form.groups"
              placeholder="请选择组"
              multiple
              clearable
              value-key="id"
              :disabled="form.accounts.length > 0"
            >
              <el-option
                v-for="item in currentGroups"
                :key="item"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="户"
            :prop="form.groups.length > 0 ? '' : 'accounts'"
          >
            <el-select
              v-model="form.accounts"
              placeholder="请选择户"
              multiple
              clearable
              :disabled="form.groups.length > 0"
              value-key="id"
            >
              <el-option
                v-for="item in currentAccounts"
                :key="item"
                :label="item.account"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
              color="#626aef"
              @click="submitForm(formRef)"
              style="width: 100%"
              :loading="loading"
            >
              撤单
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </Page>
</template>

<style>
.revoke-form .el-input {
  --el-input-width: 220px;
}

.revoke-form .el-select {
  --el-select-width: 220px;
}
</style>
